using System;
using System.Globalization;

namespace Rhizome.Internal
{
	internal static class ConvertExtension
	{
		private static readonly CultureInfo Fmt = new CultureInfo("en-US");

		public static object ChangeType(this object value, Type toType)
		{
			return Convert.ChangeType(value, toType, Fmt);
		}

		public static T ChangeType<T>(this object value)
		{
			return (T)Convert.ChangeType(value, typeof(T), Fmt);
		}

		public static object ConvertValue(this string s)
		{
			if (s.Equals(Boolean.TrueString, StringComparison.InvariantCultureIgnoreCase)) return true;
			if (s.Equals(Boolean.FalseString, StringComparison.InvariantCultureIgnoreCase)) return false;

			int i;
			if (Int32.TryParse(s, NumberStyles.Integer, Fmt, out i)) return i;

			double d;
			if (Double.TryParse(s, NumberStyles.Float, Fmt, out d)) return d;

			return s;
		}
	}
}